<?php
/**
 * appRain v 0.1.x
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */

class Component_Appstore_Helpers_Checkout extends Component_Appstore_Helpers_Data
{
    public function getCountryBox($name=null,$selected='US',$options=array(),$type='Shipping'){
		
		$CountryList = $this->CountryList(
			((strtolower($type) == 'shipping') ? 'Active' : 'All')
		);

		$htmlElement = App::Html()
		->selectTag(
			$name,
			App::Utility()->get1DArr($CountryList,'code','name'),
			$selected,
			$options,
			array('off_blank'=>'Yes')
		);
		
		return ($htmlElement);
	}
	
    public function getStateBox($code='US',$name=null,$selected='',$options=array(),$type='Shipping'){
	
		$Country = App::InformationSet('Countries')->findByCode($code);
		$htmlElement = App::Html()->inputTag(
				$name,
				$selected,
				$options
			);
		if($Country['states'] != ''){
			$states = App::Module('Cryptography')->jsonDecode($Country['states']);	
		
			$htmlElement = App::Html()
			->selectTag(
				$name,
				$states,
				$selected,
				$options,
				array('off_blank'=>'Yes')
			);
		}
		return ($htmlElement);
	}
	
	public function calculateShippingByProduct($productid=null){
	
		$productid = isset($productid) ? $productid : $this->getProductId();
		$Porduct = App::InformationSet('product')->findById($productid);
		if(empty($Porduct['shippingmethod'])){
			return 0;
		}
		
		$ShippingRole = App::CategorySet('shippingrole')->findById($Porduct['shippingmethod']);		
		$ShippingRoleData = array();
		if($ShippingRole['description'] !=''){
			$ShippingRoleData = unserialize($ShippingRole['description']);
		}
		$country = $this->getCountry();		

		$defaultrate = isset($ShippingRoleData['Shipping']['defaultrate']) ? $ShippingRoleData['Shipping']['defaultrate'] : 0;
		
		$RatePerQty = 0;
		if(isset($ShippingRoleData['Countries'][$country]) and $ShippingRoleData['Countries'][$country] != ''){
			$RatePerQty = $ShippingRoleData['Countries'][$country];
		}
		else {
			$RatePerQty = $defaultrate;
		}
		
		$ShippingRate = $RatePerQty;
		if($ShippingRoleData['Shipping']['calmethod'] == 'multiplybyqty'){
			$ShippingRate = $RatePerQty * $this->getQty();
		}
		else if($ShippingRoleData['Shipping']['calmethod'] == 'setbyscript' and isset($ShippingRoleData['Shipping']['script'])){			

			$fxname = "calShipping" .$Porduct['shippingmethod'];
			if(!function_exists($fxname)){
				$phpCode = '
					function ' . $fxname . '($Shipping){
						' . $ShippingRoleData['Shipping']['script'] . '
					}
				';			
				eval($phpCode);
			}			
			$ShippingRate = $fxname($this);
		}
		
		return $ShippingRate;
	}
	
	public function getShippingCountry($code=null){
		
		if(!isset($code)){		
			$code = App::Session()->Read('shipping_country_code');
		}
		
		return !empty($code) ? $code : 	App::Config()->Setting('appstoresettings_default_country_code','US');
	}
	
	public function CalculateShipping(){	
		
		$cartinfo = $this->getCartInfo();
		$cuntry = $this->getShippingCountry();		
		$totalCost = 0;
		foreach($cartinfo as $pid => $quote){
			$totalCost += $this->setProductId($pid)
				->setQty($quote['qty'])
				->setCountry($cuntry)					
				->calculateShippingByProduct();
		}		
		return $totalCost;
	}
	
	public function hasShipping(){
		$cartinfo = $this->getCartInfo();		
		
		$flag = false;
		foreach($cartinfo as $pid => $quote){
			$Porduct = App::InformationSet('product')->findById($pid);			
			if(!empty($Porduct['shippingmethod'])){
				$flag = true;
			}
		}	
		return $flag;
	}
	
	public function CalculateOrderInCartCost(){
		$cartinfo = $this->getCartInfo();
		
		$totalCost = 0;
		foreach($cartinfo as $pid => $quote){
			$Product = App::InformationSet('product')->findById($pid);
			$totalCost += $Product['price'] * $quote['qty'];
		}
		
		return $totalCost;
	}
	
	public function executeCouponCode($code){
		if(empty($code)){
				throw new AppException('Please enter a valid code.');
		}
		else {
			$Coupon = App::InformationSet('discountcoupon')->find("code='{$code}' AND status='Active'");
			if(empty($Coupon)){
				throw new AppException('Please enter a valid code.');
			}
			else{
				if($Coupon['calmethod'] == 'flatamount' && $Coupon['amount'] > $this->CalculateOrderInCartCost()){
					throw new AppException('Coupon amount can not grater then order amount');					
				}
			}
		}
		
		App::Session()->Write('discount_id',$Coupon['id']);		
		App::InformationSet('discountcoupon')
			->setId($Coupon['id'])
			->setStatus('Redeemed')
			->Save();
						
	}

	public function calculateDiscount(){
	
		$T = $this->CalculateOrderInCartCost();
		
		$discount = App::Session()->Read('discount_id');
		if(empty($discount)){
			return 0;
		}
				
		$discount = App::InformationSet('discountcoupon')->findById($discount);
		if($discount['calmethod'] == 'flatamount'){
			$discountAmount =  $discount['amount'];
		}
		else {
			$discountAmount = round((($T * $discount['amount'])/100),2);
		}
		
		if(!function_exists('calculate_discount')){
			$phpCode =  App::Config()->Setting('discountcalculationphpblock');
			eval($phpCode);
		}
		
		if(function_exists('calculate_discount')){
			$manualCalculation =  calculate_discount($discount,$T);
			if(!empty($manualCalculation)){
				$discountAmount = $manualCalculation;
			}
		}
		
		return $discountAmount;
	}

	public function calculateOrderTotal(){
	
		$S = $this->calculateShipping();
		$T = $this->CalculateOrderInCartCost();
		$D = $this->calculateDiscount();
		
		return ($S + $T) - $D;
	}	
	
	public function getChckoutSummaryHtml(){
	
		$curr = App::Config()->setting('currency','USD');
		$Html = "<ol class=\"checkout-order-summary\">";
			$Html .= "<li><label>Item Amount</label> <span> {$curr}{$this->CalculateOrderInCartCost()}</span></li>";			
			
			if(App::Config()->Setting('enablediscountmodule','Yes') == 'Yes'){
				$Html .= "<li><label>Discount Amount</label> <span> {$curr}{$this->calculateDiscount()}</span></li>";
			}			

			if($this->calculateShipping() > 0){
				$Html .= "<li><label>Shipping Amount</label> <span>{$curr}{$this->calculateShipping()}</span></li>";			
			}
			
			$Html .= "<li class=\"grendtotal\"><label>Total Amount</label> <span> {$curr}{$this->calculateOrderTotal()}</span></li>";			
		$Html .= "</ol>";
		
		return $Html;
	}
}